//
//  M1WsInfoViewController.m
//  NewMarryU
//
//  Created by apple on 2018/7/13.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1WsInfoViewController.h"
#import "M1WsInfoView.h"
#import "M1WsSexView.h"
#import "M1CerViewController.h"
#import "M1RealNameViewController.h"
#import "M1CLLocationManage.h"
@interface M1WsInfoViewController ()<UINavigationBarDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>
@property (nonatomic ,strong) UIButton *m1_headBtn;
@property (nonatomic ,strong) UIButton *m1_commitBtn;
@property (nonatomic ,strong) M1WsInfoView *m1_nameView;
@property (nonatomic ,strong) M1WsInfoView *m1_birthdayView;
@property (nonatomic ,strong) M1WsInfoView *m1_addressView;
@property (nonatomic ,strong) M1WsSexView *m1_sexView;
@property (nonatomic ,strong) M1WsInfoView *m1_hightView;
@property (nonatomic ,strong) M1WsInfoModel *m1_wsInfoModel;
@end

@implementation M1WsInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"完善资料";
    [self m1_banPopGesture];
    
    NSArray *m1_array1 = @[@"两年内",@"一年内"];
    NSArray *m1_array2 = @[@"我就是我 是颜色不一样的烟火",@"白茶清欢无别事，我在等风也等你。",@"一辈子其实不长，能够遇见你，是件多么幸运的事。",@"在最好的时候遇见你，是我的幸运。",@"一次就好，我陪你去看天荒地老。",@"你还不来，我怎敢老去。"];
    _m1_wsInfoModel = [M1WsInfoModel new];
    _m1_wsInfoModel.plan_marry_time = m1_array1[rand()%2];
    _m1_wsInfoModel.birthday = @"1990-01-01";
    _m1_wsInfoModel.about_me = m1_array2[rand()%6];
    if ([M1SaveTool m1_Location]) {
        _m1_wsInfoModel.abode = [M1SaveTool m1_Location][@"city"];
    }
    [self m1_createUI];
}
-(void)m1_nameTfChage:(UITextField *)TF{
    UITextRange *selectedRange = [TF markedTextRange];
    UITextPosition *position = [TF positionFromPosition:selectedRange.start offset:0];
    if (!position){
        NSString *tf = TF.text;
        if ([tf m1_cLength] > 12) {
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
            for(int i =0; i < [tf length]; i++)
            {
                [array addObject:[tf substringWithRange:NSMakeRange(i,1)]];
            }
            float length = 0;
            for (int i = 0; i<array.count ; i++) {
                NSString *news = array[i];
                length += [news m1_cLength];
                if (length > 12) {
                    tf = [tf substringToIndex:i];
                    break;
                }
            }
        }
        TF.text = tf;
    }
    _m1_wsInfoModel.name = [_m1_nameView.m1_TF.text m1_removeWhitespace];
    [self m1_checkInfo];
}

-(void)m1_back{
    WEAKSELF;
    [M1Alert m1_alertWithTitle:nil message:@"您确定要放弃可能遇见的缘分吗？" buttonTitles:@[@"取消",@"确认"] action:^(NSInteger index) {
        if (index == 1) {
            NSArray *m1_vcs = weakSelf.navigationController.viewControllers;
            if ([m1_vcs[0] isKindOfClass:[M1ShuntVC class]]) {
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            }else{
                NSInteger vcindex = 0;
                for (int i=0; i<m1_vcs.count; i++) {
                    if ([m1_vcs[i] isKindOfClass:[M1LoginVC class]]) {
                        vcindex = i;
                        break;
                    }
                }
                [M1User remove];
                [[EMClient sharedClient] logout:YES];
                [weakSelf.navigationController popToViewController:[m1_vcs objectAtIndex:vcindex-1] animated:YES];
            }
        }
        
    }];
}

-(void)m1_commitInfo{
    
    WEAKSELF;
    [[M1FileUpload manager] m1_uploadImages:@[_m1_wsInfoModel.AvatarImage] progress:^(CGFloat progress) {
        
    } completion:^(NSArray<NSString *> * _Nullable urls, NSArray<NSDictionary *> * _Nullable pictures, NSError * _Nullable error) {
        if (!error) {
            weakSelf.m1_wsInfoModel.avatar = pictures[0];
            [weakSelf m1_uploadInfo];
        }
    }];
    

}

-(void)m1_uploadInfo{
    NSData *m1_avararData = [NSJSONSerialization dataWithJSONObject:_m1_wsInfoModel.avatar options:NSJSONWritingPrettyPrinted error:nil];
    NSString *m1_avararJson = [[NSString alloc] initWithData:m1_avararData encoding:NSUTF8StringEncoding];
    NSDictionary *m1_params = @{@"avatar":m1_avararJson,
                                @"birthday":_m1_wsInfoModel.birthday,
                                @"name":_m1_wsInfoModel.name,
                                @"abode":_m1_wsInfoModel.abode,
                                @"gender":_m1_wsInfoModel.gender,
                                @"about_me":_m1_wsInfoModel.about_me,
                                @"plan_marry_time":_m1_wsInfoModel.plan_marry_time,
                                @"annual_income":@"10w~20w",
                                @"high":_m1_wsInfoModel.high
                                };
    WEAKSELF;
    [M1HttpNet requestWithMethod:m1_update_info_url params:m1_params success:^(id resDic, NSInteger code, NSString *message) {
        M1CerViewController *m1_cerVC = [[M1CerViewController alloc]init];
        [weakSelf.navigationController pushViewController:m1_cerVC animated:YES];
    } fail:^(id resDic, NSInteger code, NSString *message) {
        [M1Alert m1_alertWithTitle:nil message:message];
    } showAni:YES];
}
-(void)m1_checkInfo{
    if (_m1_wsInfoModel.AvatarImage&&_m1_wsInfoModel.abode.length>0&&_m1_wsInfoModel.name.length>0&&_m1_wsInfoModel.gender.length >0&&_m1_wsInfoModel.high.length >0) {

        [_m1_commitBtn setBackgroundImage:[UIImage imageNamed:@"btn_color"] forState:0];
            _m1_commitBtn.userInteractionEnabled = YES;
    }else{
        _m1_commitBtn.userInteractionEnabled = NO;
        [_m1_commitBtn setBackgroundImage:[UIImage new] forState:0];
    }
}

-(void)m1_headBtnClick{
    [self.view endEditing:YES];
    M1SheetView *m1_sheet = [[M1SheetView alloc]initWithTitles:@[@"拍照",@"从相册选择"]];
    [m1_sheet m1_show];
    WEAKSELF;
    m1_sheet.click = ^(NSInteger index) {
        
        UIImagePickerControllerSourceType sourceType;
        
        if (index == 0) {
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
                NSString *errorStr = @"应用相机权限受限,请在设置中启用";
                return;
            }else{
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                }
            }
        }else{
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            }
        }
        UIImagePickerController *m1_picker = [[UIImagePickerController alloc] init];
        m1_picker.editing = YES;
        m1_picker.sourceType = sourceType;
        m1_picker.delegate = weakSelf;
        m1_picker.allowsEditing = YES;
        if (index == 0) {
            m1_picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        }
        
        [weakSelf presentViewController:m1_picker animated:YES completion:nil];
    };
    
}

- (void)extracted:(NSString *)max min:(NSString *)min {
    WEAKSELF;
    [BRDatePickerView showDatePickerWithTitle:@"出生日期" dateType:BRDatePickerModeYMD defaultSelValue:_m1_wsInfoModel.birthday minDate:[NSDate m1_dateWithString:min] maxDate:[NSDate m1_dateWithString:max] isAutoSelect:NO themeColor:nil resultBlock:^(NSString *selectValue) {
        weakSelf.m1_birthdayView.m1_TF.text = selectValue;
        weakSelf.m1_wsInfoModel.birthday = selectValue;
        [weakSelf m1_checkInfo];
    }];
}
-(void)m1_high{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
    for (int i=140; i<=200; i++) {
        [array addObject:@(i).stringValue];
    }
    WEAKSELF;
    [BRStringPickerView showStringPickerWithTitle:@"身高" dataSource:array defaultSelValue:_m1_wsInfoModel.high resultBlock:^(id selectValue)  {
        weakSelf.m1_hightView.m1_TF.text = [NSString stringWithFormat:@"%@cm",selectValue];
        weakSelf.m1_wsInfoModel.high = selectValue;
        [weakSelf m1_checkInfo];
    }];
}
-(void)m1_birthday{
    [self.view endEditing:YES];
    NSString *dateStr = [NSDate m1_stringDate];
    NSString *year = [dateStr componentsSeparatedByString:@"-"][0];
    NSString *max  = [dateStr stringByReplacingOccurrencesOfString:year withString:[NSString stringWithFormat:@"%d",[year intValue]-18]];
    NSString *min  = [dateStr stringByReplacingOccurrencesOfString:year withString:[NSString stringWithFormat:@"%d",[year intValue]-100]];
    [self extracted:max min:min];
}

-(void)m1_address{
    [self.view endEditing:YES];
    WEAKSELF;
    NSArray *m1_default = nil;
    if (_m1_wsInfoModel.abode.length >0) {
        m1_default = [_m1_wsInfoModel.abode componentsSeparatedByString:@"-"];
    }
    
    [BRAddressPickerView showAddressPickerWithShowType:BRAddressPickerModeCity defaultSelected:m1_default isAutoSelect:NO themeColor:nil resultBlock:^(BRProvinceModel *province, BRCityModel *city, BRAreaModel *area) {
        weakSelf.m1_addressView.m1_TF.text = [NSString stringWithFormat:@"%@-%@",province.name,city.name];
        weakSelf.m1_wsInfoModel.abode = [NSString stringWithFormat:@"%@-%@",province.name,city.name];
        [weakSelf m1_checkInfo];
    } cancelBlock:^{
        
    }];
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([textField isFirstResponder]) {
        if ([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage]) {
            [M1Alert m1_alertWithTitle:nil message:@"不支持Emoji表情"];
            return NO;
        }
        if ([string m1_includEmoji]) {
            [M1Alert m1_alertWithTitle:nil message:@"不支持Emoji表情"];
            return NO;
        }
    }
    return YES;
}
#pragma mark - imagePickerController delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    //获取到的图片
    UIImage * image = [info valueForKey:UIImagePickerControllerEditedImage];
    
    image = m1_FixImageOrientation(image);
    
    [_m1_headBtn setBackgroundImage:image forState:0];
    
    self.m1_wsInfoModel.AvatarImage = image;
    
    [self m1_checkInfo];
}


-(void)m1_createUI{
    UIView *m1_bgView = [[UIView alloc]init];
    m1_bgView.layer.shadowColor = [UIColor m1_colorHex:0xCAD0DC].CGColor;
    m1_bgView.layer.shadowOpacity = 0.25;
    m1_bgView.layer.shadowOffset = CGSizeMake(1, 1);
    m1_bgView.layer.cornerRadius = 13;
    m1_bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:m1_bgView];
    
    [m1_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.right.offset(-20);
        make.top.offset(iPhoneX?108:(iPhone5?64:70));
    }];
    
    float with = 150;
    if (iPhone5) {
        with = 110;
    }
    
    if (iPhone4) {
        with = 80;
    }
    _m1_headBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_m1_headBtn setBackgroundImage:[UIImage imageNamed:@"ws_add"] forState:0];
    _m1_headBtn.imageView.contentMode = UIViewContentModeScaleAspectFill;
    _m1_headBtn.clipsToBounds = YES;
    [_m1_headBtn addTarget:self action:@selector(m1_headBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _m1_headBtn.layer.cornerRadius = with/2;
    [m1_bgView addSubview:_m1_headBtn];
    
    [_m1_headBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(m1_bgView);
        make.top.offset(iPhone5?20:(iPhone6?30:40));
        make.width.height.mas_offset(with);
    }];
    
    UILabel *m1_LB1 = [[UILabel alloc]init];
    m1_LB1.font = m1_font(12);
    m1_LB1.text= @"*请上传本人真实照片";
    m1_LB1.textColor = [UIColor m1_colorHex:0xFF5F70];
    [self.view addSubview:m1_LB1];
    
    if (iPhone4) {
        [m1_LB1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(m1_bgView.mas_centerX);
            make.top.equalTo(_m1_headBtn.mas_bottom);
        }];
    }else{
        [m1_LB1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(m1_bgView.mas_centerX);
            make.top.equalTo(_m1_headBtn.mas_bottom).offset(iPhone5?20:23);
        }];
    }
   
    
    _m1_nameView = [[M1WsInfoView alloc]init];
    _m1_nameView.m1_touchBtn.hidden = YES;
    _m1_nameView.m1_titleLB.text = @"昵称";
    _m1_nameView.m1_TF.delegate = self;
    _m1_nameView.m1_TF.placeholder = @"填写您的昵称";
    [_m1_nameView.m1_TF addTarget:self action:@selector(m1_nameTfChage:) forControlEvents:UIControlEventAllEditingEvents];
    [m1_bgView addSubview:_m1_nameView];
    
    if (iPhone4) {
        [_m1_nameView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.height.mas_offset(iPhone5?45:54);
            make.top.equalTo(m1_LB1.mas_bottom).offset(10);
        }];
    }else{
        [_m1_nameView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.height.mas_offset(iPhone5?45:54);
            make.top.equalTo(m1_LB1.mas_bottom).offset(iPhone5?10:20);
        }];
    }
    
    
  
    
    _m1_sexView = [[M1WsSexView alloc]init];
    [m1_bgView addSubview:_m1_sexView];
    [_m1_sexView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.mas_offset(iPhone5?45:54);
        make.top.equalTo(_m1_nameView.mas_bottom);
    }];
    WEAKSELF;
    _m1_sexView.selectSex = ^(NSInteger sex) {
        weakSelf.m1_wsInfoModel.gender = @(sex).stringValue;
        [weakSelf m1_checkInfo];
    };
    
    _m1_hightView = [[M1WsInfoView alloc]init];
    _m1_hightView.m1_titleLB.text = _m1_wsInfoModel.high.length >0?[NSString stringWithFormat:@"%@cm",_m1_wsInfoModel.high]:@"";
    _m1_hightView.m1_titleLB.text = @"身高";
    _m1_hightView.m1_TF.placeholder = @"请选择身高";
    _m1_hightView.m1_TF.userInteractionEnabled = NO;
    [_m1_hightView.m1_touchBtn addTarget:self action:@selector(m1_high) forControlEvents:UIControlEventTouchUpInside];
    [m1_bgView addSubview:_m1_hightView];
    [_m1_hightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.mas_offset(iPhone5?45:54);
        make.top.equalTo(_m1_sexView.mas_bottom);
    }];
    
    _m1_birthdayView = [[M1WsInfoView alloc]init];
    _m1_birthdayView.m1_titleLB.text = @"出生日期";
    _m1_birthdayView.m1_TF.placeholder = @"填写您的出生日期";
    _m1_birthdayView.m1_TF.userInteractionEnabled = NO;
    _m1_birthdayView.m1_TF.text = _m1_wsInfoModel.birthday;
    [_m1_birthdayView.m1_touchBtn addTarget:self action:@selector(m1_birthday) forControlEvents:UIControlEventTouchUpInside];
    [m1_bgView addSubview:_m1_birthdayView];
    [_m1_birthdayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.mas_offset(iPhone5?45:54);
        make.top.equalTo(self.m1_hightView.mas_bottom);
    }];
    
    
    
    _m1_addressView = [[M1WsInfoView alloc]init];
    _m1_addressView.m1_titleLB.text = @"所在地";
    _m1_addressView.m1_TF.placeholder = @"填写您的所在地";
    _m1_addressView.m1_line.hidden = YES;
    _m1_addressView.m1_TF.text= _m1_wsInfoModel.abode;
    _m1_addressView.m1_TF.userInteractionEnabled = NO;
    [_m1_addressView.m1_touchBtn addTarget:self action:@selector(m1_address) forControlEvents:UIControlEventTouchUpInside];
    [m1_bgView addSubview:_m1_addressView];
    [_m1_addressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.mas_offset(iPhone5?45:54);
        make.top.equalTo(_m1_birthdayView.mas_bottom);
        make.bottom.offset(0);
    }];
    [[M1CLLocationManage shareInstance] m1_getLocation:^(NSString *province, NSString *city) {
        weakSelf.m1_wsInfoModel.abode = [NSString stringWithFormat:@"%@-%@",province,city];
        weakSelf.m1_addressView.m1_TF.text= weakSelf.m1_wsInfoModel.abode;
    } faild:^(NSString *error) {
        
    }];
    
    _m1_commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_m1_commitBtn setTitle:@"提交" forState:0];
    [_m1_commitBtn setTitleColor:[UIColor whiteColor] forState:0];
    _m1_commitBtn.titleLabel.font = m1_font(16);
    _m1_commitBtn.layer.cornerRadius = 25;
    _m1_commitBtn.clipsToBounds = YES;
    _m1_commitBtn.userInteractionEnabled = NO;
    [_m1_commitBtn addTarget:self action:@selector(m1_commitInfo) forControlEvents:UIControlEventTouchUpInside];
    _m1_commitBtn.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    [self.view addSubview:_m1_commitBtn];
    
    [_m1_commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.height.mas_offset(50);
        make.width.mas_offset(270);
        make.top.equalTo(m1_bgView.mas_bottom).offset(iPhone5?10:(iPhone6?20:34));
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


@implementation M1WsInfoModel
@end
